//
//  CommentSendView.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/14.
//

import UIKit

let SendHeight = 58.0

class CommentSendView: UIView {
    
    lazy var bgView: UIView = {
        let view = UIView()
        view.backgroundColor = .init(named: "white_F7F7F7")
        view.wn_cornerWithBorder(4)
        return view
    }()
    
    lazy var textView: IQTextView = {
        let view = IQTextView()
        view.placeholder = "Write your comment here..."
        view.font = .wn_font(name: .regular, size: 16)
        view.returnKeyType = .done
        view.keyboardDismissMode = .none
        view.textColor = .black
        view.tintColor = .init(named: "red_FE95B4")
        view.backgroundColor = .init(named: "white_F7F7F7")
        view.textContainer.lineFragmentPadding = 10
        view.textContainerInset = .init(top: 10, left: 0, bottom: 10, right: 0)
        view.delegate = self
        return view
    }()
    
    lazy var sendBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "read_comment_send"), for: .normal)
        btn.imageView?.contentMode = .scaleAspectFit
        btn.imageEdgeInsets = .init(top: 10, left: 10, bottom: 10, right: 10)
        btn.rx.tap.bind { [weak self] in
            self?.sendComment()
        }.disposed(by: rx.disposeBag)
        btn.isEnabled = false
        return btn
    }()
    
    var sendClosure: StringClosure?
    
    var heightClosure: CGFloatClosure?
    
    var currentText: String = "" {
        didSet {
            let str = currentText.trimmingCharacters(in: .whitespacesAndNewlines)
            sendBtn.setImage(UIImage(named: str.count == 0 ? "read_comment_send" : "read_comment_send_sel"), for: .normal)
            sendBtn.isEnabled = str.count != 0
        }
    }
    
    var viewHeight: CGFloat = SendHeight
    
    var isComment : Bool = true
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        addSubview(bgView)
        bgView.addSubview(sendBtn)
        bgView.addSubview(textView)
        bgView.snp.makeConstraints { (make) in
            make.top.equalTo(8)
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.bottom.equalTo(-8-TabBarMargin)
        }
        sendBtn.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.right.equalTo(0)
            make.width.height.equalTo(44)
        }
        textView.snp.makeConstraints { (make) in
            make.top.left.bottom.equalTo(0)
            make.right.equalTo(sendBtn.snp.left).offset(-10)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension CommentSendView: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        if textView.text.count > WNRegex.CommentMaxLen {
            let selectRange = textView.markedTextRange
            if let selectRange = selectRange {
                let position = textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
            let textContent = textView.text
            let textNum = textContent?.count
            if textNum! > WNRegex.CommentMaxLen {
                let index = textContent?.index((textContent?.startIndex)!, offsetBy: WNRegex.CommentMaxLen)
                let str = String(textContent![..<index!])
                textView.text = str
            }
            WNHUD.wn_show("Max of comments in \(WNRegex.CommentMaxLen) words")
            WNThread.wn_runInMainThread {
                self.textView.selectedTextRange = self.textView.textRange(from: self.textView.endOfDocument, to: self.textView.endOfDocument)
            }
        }
        currentText = textView.text
        let height = heightForTextView(textView: textView, fixedWidth: ScreenW - 75)
        viewHeight = (height > 88) ? 88 : height
        heightClosure?(viewHeight+16+TabBarMargin)
    }
    
    func heightForTextView(textView: UITextView, fixedWidth: CGFloat) -> CGFloat {
        let size = CGSize(width: fixedWidth, height: 16)
        let constraint = textView.sizeThatFits(size)
        return constraint.height
    }
    
    @objc func sendComment() {
        let text = currentText.trimmingCharacters(in: .whitespacesAndNewlines)
        sendClosure?(text)
    }
}
